﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text.RegularExpressions;

namespace AIC_Notification
{
    class SchoolListForAC : FormatedReport
    {
        private int FontSize = 12;
        private int CellWidth;
        private int MaxSchoolColumn = 0;
        private int SCHOOL_PER_ROW = 7;

        static string[] SchoolTypeBkColor = new string[] { "", "#CCFFCC", "#FFFFCC", "#FFDDAA", "#F8D3D3" };
        static string[] SchoolTypeTxColor = new string[] { "", "black", "black", "black", "black" };
        static string[] SchoolTypeText    = new string[] { "Unknown", "Safety", "Solid", "Reach", "Reach+" };

        public IList<SOF_Application> Students = null;

        public SchoolListForAC()
        {
            ReportTitle = "Application Schools (Consultant)";
        }

        public override string GetSubject()
        {
            return String.Format("{0} - {1} - {2:d}", ReportTitle, SubjectID, Global.Now());
        }

        public override string GenerateLedger()
        {
            string htmlLedger = "";

            htmlLedger += "<tr><td>";
            htmlLedger += "<div style=\"text-align:center; font-size: 11px;\">";
            htmlLedger += "<b><u>Application Type</u></b>: <span style=\"background-color: yellow;\">Yellow</span> = Early Application; ";
            htmlLedger += "<span style=\"background-color: #FFE4B5;\">Light Orange</span> = Early Application 2; ";
            htmlLedger += "<span style=\"background-color: #B0E2FF;\">Light Blue</span> = No Supplement; ";
            htmlLedger += "</div>";
            htmlLedger += "<div style=\"text-align:center; font-size: 11px;\">";
            htmlLedger += "<b><u>School Type</u></b>: ";
            htmlLedger += "<b>NU</b> = National University; <b>LAC</b> = Liberal Arts College; <b>OU</b> = Other University";
            htmlLedger += "</div>";
            htmlLedger += "<div style=\"text-align:center; font-size: 11px;\">";
            htmlLedger += "<b><u>Application Category</u></b>: ";
            htmlLedger += "<span style=\"background-color: #F8D3D3;\">Red</span> = Super Reach School; ";
            htmlLedger += "<span style=\"background-color: #FFDDAA;\">Orange</span> = Reach School; ";
            htmlLedger += "<span style=\"background-color: #FFFFCC;\">Yellow</span> = Match School; ";
            htmlLedger += "<span style=\"background-color: #CCFFCC;\">Green</span> = Safety School; ";
            htmlLedger += "<span>White</span> = Unknown School";
            htmlLedger += "</div>";
            htmlLedger += "<div style=\"text-align:center; font-size: 11px;\">";
            htmlLedger += "<b><u>Rally Status</u></b>: ";
            htmlLedger += "<span style=\"background-color: #F8D3D3;\">Red</span> = Behind; ";
            htmlLedger += "<span style=\"background-color: #FFFFCC;\">Yellow</span> = On Track; ";
            htmlLedger += "<span style=\"background-color: #CCFFCC;\">Green</span> = Completed; ";
            htmlLedger += "</div>";

            htmlLedger += "</td></tr>";

            return htmlLedger;
        }

        public override void SendReportAsEmail()
        {
            foreach (var _teacher in TeacherDB.Teachers)
            {
                string HTMLBody;

                // Only for AC with one student or more
                if (_teacher.Students.Count > 0)
                {
                    Students = _teacher.Students;
                    // TeacherInContext = _teacher.Name;
                    HeaderInformation = _teacher.Name;

                    FileName = String.Format("{0}-{1}-{2:yyyyMMdd-HHmmss}.htm", ReportTitle, _teacher.Name, Global.Now());
                    Global.SysUtil.Log("Generating Report: " + FileName);

                    HTMLBody = GetHTMLBody();

                    // Save Report to File
                    SaveReportToFile(FileName, HTMLBody);

                    // Send Report E-mail
                    toRecipients.Clear();
                    ccRecipients.Clear();

                    // Send to teacher
                    toRecipients.Add(_teacher.Email);

                    // Add AM/VVIP if AC or Both
                    if (_teacher.Type == "Academic Consultant" || _teacher.Type == "Both")
                    {
                        string[] AcademicManagers = TeacherDB.GetAcademicManager((CityDB.CityEnum)CityDB.GetCityByName(_teacher.City).CityNumber);
                        foreach (var AcademicManager in AcademicManagers)
                            AddAcademicManagerEmail(AcademicManager);
                    }

                    SubjectID = _teacher.Name;

                    Global.SysUtil.SendHTML(toRecipients, ccRecipients, GetSubject(), HTMLBody);
                }
            }
        }

        private void CalculateTableFormatParam()
        {
            int MaxSupplimentSchool = 0;
            int MaxNonSupplimentSchool = 0;

            // Calculate Max # of Suppliment School
            foreach (var student in Students)
            {
                int SchoolCount_S = 0;
                int SchoolCount_NS = 0;

                foreach (var School in student.Schools)
                {
                    if (School.ListType == "School")
                    {
                        if (!School.NonSuppliment)
                        {
                            SchoolCount_S += 1;
                            if (SchoolCount_S > MaxSupplimentSchool)
                                MaxSupplimentSchool = SchoolCount_S;
                        }
                        else
                        {
                            SchoolCount_NS += 1;
                            if (SchoolCount_NS > MaxNonSupplimentSchool)
                                MaxNonSupplimentSchool = SchoolCount_NS;
                        }
                    }
                }
            }

            MaxSchoolColumn = MaxSupplimentSchool > MaxNonSupplimentSchool ? MaxSupplimentSchool : MaxNonSupplimentSchool;
        }

        private string InsertSchoolListStatistics(SOF_Application ApplyingStudent, int FontSize, int RowSpan = 1)
        {
            string SchoolListStatsHTML = "";
            int SchoolListFontSize = FontSize - 1;
            string SchoolListBkColor = "";

            int UC_ReachTotal = ApplyingStudent.ApplicationStats.SchoolTypeStats.UC_Reach +
                ApplyingStudent.ApplicationStats.SchoolTypeStats.UC_SuperReach;
            int ReachTotal = ApplyingStudent.ApplicationStats.SchoolTypeStats.Reach +
                ApplyingStudent.ApplicationStats.SchoolTypeStats.SuperReach +
                UC_ReachTotal;

            int UC_MatchTotal = ApplyingStudent.ApplicationStats.SchoolTypeStats.UC_Match;
            int MatchTotal = ApplyingStudent.ApplicationStats.SchoolTypeStats.Match + UC_MatchTotal;

            int UC_SafetyTotal = ApplyingStudent.ApplicationStats.SchoolTypeStats.UC_Safety;
            int SafetyTotal = ApplyingStudent.ApplicationStats.SchoolTypeStats.Safety + UC_SafetyTotal;

            // Mark School Stats as Green if 1. ED Accepted or EA Selected, or 2. Completed 10 Suppliment Schools
            if (ApplyingStudent.StudentObject != null && 
                (ApplyingStudent.StudentObject.IsEarlyComplete() || ApplyingStudent.ApplicationStats.SchoolEssayCompletionStats.CompletedSchools >= 10)
                )
                SchoolListBkColor = String.Format("style=\"background-color: {0};\"", SchoolTypeBkColor[1]);

            // Create School Statistics Cell
            SchoolListStatsHTML += String.Format("<td rowspan=\"{0}\" {1}>", RowSpan, SchoolListBkColor);

            // Insert School Count Lines
            SchoolListStatsHTML += String.Format("<div style=\"font-size: {0}px;\"><u><b>School Count:</b></u></div>", FontSize);

            SchoolListStatsHTML += String.Format("<div style=\"font-size: {0}px;\">Supplement: {1}/{2}</div>",
                SchoolListFontSize,
                ApplyingStudent.ApplicationStats.SchoolEssayCompletionStats.CompletedSchools,
                ApplyingStudent.ApplicationStats.SchoolTypeStats.SupplimentSchool);

            SchoolListStatsHTML += String.Format("<div style=\"font-size: {0}px;\">Non-Supplement: {1}</div>",
                SchoolListFontSize,
                ApplyingStudent.ApplicationStats.SchoolTypeStats.NonSupplimentSchool);

            // Insert School Type Count Lines
            SchoolListStatsHTML += String.Format("<div style=\"font-size: {0}px;\"><u><b>Type Count:</b></u></div>", FontSize);

            SchoolListStatsHTML += String.Format("<div style=\"font-size: {0}px;\">Reach: {1}/{2}{3}</div>",
                SchoolListFontSize,
                ApplyingStudent.ApplicationStats.SchoolTypeStats.ReachAccepted,
                ReachTotal,
                UC_ReachTotal > 0 ? String.Format(" (UC: {0})", UC_ReachTotal) : "");
            SchoolListStatsHTML += String.Format("<div style=\"font-size: {0}px;\">Solid: {1}/{2}{3}</div>",
                SchoolListFontSize,
                ApplyingStudent.ApplicationStats.SchoolTypeStats.SolidAccepted,
                MatchTotal,
                UC_MatchTotal > 0 ? String.Format(" (UC: {0})", UC_MatchTotal) : "");
            SchoolListStatsHTML += String.Format("<div style=\"font-size: {0}px;\">Safety: {1}/{2}{3}</div>",
                SchoolListFontSize,
                ApplyingStudent.ApplicationStats.SchoolTypeStats.SafetyAccepted,
                SafetyTotal,
                UC_SafetyTotal > 0 ? String.Format(" (UC: {0})", UC_SafetyTotal) : "");
            SchoolListStatsHTML += String.Format("<div style=\"font-size: {0}px;\">Unknown: {1}</div>",
                SchoolListFontSize,
                ApplyingStudent.ApplicationStats.SchoolTypeStats.Unknown);

            SchoolListStatsHTML += "</td>";

            return SchoolListStatsHTML;
        }

        private string SetSortOrder(SOF_Application student)
        {
            int KeyStudent = 0;
            if (student.StudentObject != null)
            {
                KeyStudent = student.StudentObject.KeyStudent == "0" ? 1 : 0;
            }

            return String.Format("{0}-{1}", KeyStudent, student.Name);
        }

        public override string GenerateInnerTable()
        {
            string tableBody = "";

            if (Students.Count > 0)
            {
                CalculateTableFormatParam();
                
                CellWidth = Math.Abs((100 - 30) / SCHOOL_PER_ROW);

                // Insert Header
                tableBody += "<tr>";
                tableBody += String.Format("<th style=\"background-color: #483D8B; color: white; font-size: {1}px; width: {0}%;\">Students</th>", 7, FontSize);
                tableBody += String.Format("<th style=\"background-color: #483D8B; color: white; font-size: {1}px; width: {0}%;\">Score</th>", 8, FontSize);
                tableBody += String.Format("<th style=\"background-color: #483D8B; color: white; font-size: {1}px; width: {0}%;\">SAT2 and AP</th>", 8, FontSize);
                tableBody += String.Format("<th style=\"background-color: #483D8B; color: white; font-size: {1}px; width: {0}%;\">School Statistics</th>", 7, FontSize);
                for (int i = 1; i <= SCHOOL_PER_ROW; i++)
                {
                    tableBody += String.Format("<th style=\"background-color: #483D8B; color: white; font-size: 14px; width: {0}%;\">School {1}</th>", CellWidth, i);
                }
                tableBody += "</tr>";

                // Insert School

                foreach (var student in Students)
                    student.SortOrder = SetSortOrder(student);

                IList<SOF_Application> StudentsByName = null;
                StudentsByName = Students.OrderBy(SOF_Application => SOF_Application.SortOrder).ToList(); // Order by student Name

                foreach (var student in StudentsByName)
                {
                    // Sort school list according to rally
                    var SortedSchools = student.Schools.OrderBy(SOF_WorkList => String.Format("{0}-{1}-{2}", SOF_WorkList.Rally, SOF_WorkList.NonSuppliment ? "1" : "0", SOF_WorkList.School)).ToList();

                    // 0 = 0; 1-10 = 1; 11-20 = 2;
                    int SupplimentRows = 0;
                    if (student.ApplicationStats.SchoolTypeStats.SupplimentSchool > 0)
                    {
                        SupplimentRows = ((student.ApplicationStats.SchoolTypeStats.SupplimentSchool - 1)/ SCHOOL_PER_ROW) + 1;
                    }
                    else
                        SupplimentRows = 1;

                    int NoSupplimentRows = 0;
                    if (student.ApplicationStats.SchoolTypeStats.NonSupplimentSchool > 0)
                        NoSupplimentRows = ((student.ApplicationStats.SchoolTypeStats.NonSupplimentSchool - 1)/ SCHOOL_PER_ROW) + 1;

                    int TotalRow = SupplimentRows + NoSupplimentRows;

                    // Fill in Non-Suppliment School;
                    for (int i = 1; i <= SupplimentRows; i++)
                    {
                        tableBody += "<tr>";
                        if (i == 1)
                        {
                            // Insert Basic Information AC, Student Info, Score
                            tableBody += InsertStudentName(student, FontSize, student.StudentObject != null && student.StudentObject.KeyStudent == "1" ? "#FFEC8B" : "", TotalRow);
                            tableBody += InsertStudentScore(student, FontSize, false, TotalRow);
                            tableBody += InsertSAT2andAP(student, FontSize, TotalRow);
                            tableBody += InsertSchoolListStatistics(student, FontSize, TotalRow);
                        }
                        tableBody += InsertSchoolList(student, SortedSchools, i, false);
                        tableBody += "</tr>";
                    }

                    // Fill in No Supplement Schools
                    if (student.ApplicationStats.SchoolTypeStats.NonSupplimentSchool > 0)
                    {
                        for (int i = 1; i <= NoSupplimentRows; i++)
                        {
                            tableBody += "<tr>";
                            tableBody += InsertSchoolList(student, SortedSchools, i, true);
                            tableBody += "</tr>";
                        }
                    }
                }
            }
            return tableBody;
        }

        private void GetSchoolStatus(int Rally, int Status, ref string StatusString, ref string StatusBkColor)
        {
            // Calculate School Essay Status
            if (Status == 0)
            {
                if (Rally <= RallyHelper.CurrentRally)
                {
                    StatusString = "Behind";
                    StatusBkColor = "#F8D3D3;";
                }
                else
                {
                    StatusString = "Pending";
                    StatusBkColor = "white;";
                }
            }
            else if (Status == 1)
            {
                StatusString = "Completed";
                StatusBkColor = "#CCFFCC;"; // Green
            }
            else if (Status == 2)
            {
                StatusString = "On Track";
                StatusBkColor = "#FFFFCC;";
            }
            else if (Status == 3)
            {
                StatusString = "Behind";
                StatusBkColor = "#F8D3D3;";
            }
            else if (Status == 4)
            {
                StatusString = "On Track";
                StatusBkColor = "#FFFFCC;";
            }
            else
            {
                if (Rally <= RallyHelper.CurrentRally)
                {
                    StatusString = "Behind";
                    StatusBkColor = "#F8D3D3;";
                }
                else
                {
                    StatusString = "Pending";
                    StatusBkColor = "white;";
                }
            }
        }

        private string GetAdmissionResult(SOF_Application ApplyingStudent, School ApplyingSchool)
        {
            string AdmissionResultHTML = "";
            string AdmissionResultText = "";
            string AdmissionResultBkColor = SchoolTypeBkColor[2];
            StudentAdmissionResult SchoolResult = null;

            if (ApplyingStudent != null && ApplyingSchool != null)
            {
                if (ApplyingStudent.StudentObject != null)
                SchoolResult = ApplyingStudent.StudentObject.FindAdmissionResult(ApplyingSchool);
            }
            else
                AdmissionResultHTML = "Unknown School";

            if (SchoolResult != null)
            {
                if (SchoolResult.ApplicationType == "Early Action")
                    AdmissionResultText += "EA";
                else if (SchoolResult.ApplicationType == "Early Decision")
                    AdmissionResultText += "ED";
                else if (SchoolResult.ApplicationType == "Rolling")
                    AdmissionResultText += "Rolling";
                else
                    AdmissionResultText += "RD";

                AdmissionResultText += "-";

                if (SchoolResult.ApplicationResult == "")
                    AdmissionResultBkColor = SchoolTypeBkColor[2];
                else if (SchoolResult.ApplicationResult == "Accept" || SchoolResult.ApplicationResult == "Defer Accept" || SchoolResult.ApplicationResult == "Waitlist Accept")
                    AdmissionResultBkColor = SchoolTypeBkColor[1];
                else if (SchoolResult.ApplicationResult == "Defer" || SchoolResult.ApplicationResult == "Waitlist")
                    AdmissionResultBkColor = SchoolTypeBkColor[2];
                else if (SchoolResult.ApplicationResult == "Reject" || SchoolResult.ApplicationResult == "Defer Reject")
                    AdmissionResultBkColor = SchoolTypeBkColor[4];
                else
                    AdmissionResultBkColor = SchoolTypeBkColor[2];

                AdmissionResultText += SchoolResult.ApplicationResult != "" ? SchoolResult.ApplicationResult : "Pending";

                if (SchoolResult.FinalSelection)
                    AdmissionResultText += "+";
            }
            else
            {
                AdmissionResultText = "Not in School List";
            }

            AdmissionResultHTML = String.Format("<span style=\"background-color: {0};\">{1}</span>", AdmissionResultBkColor, AdmissionResultText);

            return AdmissionResultHTML;
        }

        private string GetRanking(School ApplyingSchool)
        {
            string RankingString = "";

            if (ApplyingSchool.Type == "National Universities")
                RankingString += "NU";
            else if (ApplyingSchool.Type == "Liberal Arts Colleges")
                RankingString += "LAC";
            else if (ApplyingSchool.Type == "Other Universities")
                RankingString += "OU";

            if (ApplyingSchool.Ranking != "")
                RankingString += "-" + ApplyingSchool.Ranking;

            return RankingString;
        }

        private string InsertUCSchool(SOF_Application ApplyingStudent, string SchoolShortName, string AlternativeName)
        {
            string tableBody = "";

            School UC_School = SchoolDB.GetUCSchool(SchoolShortName);

            // Calculate School Info
            if (UC_School != null)
            {
                SchoolAdmissionStatistics.SchoolListType SchoolType = Global.SysUtil.CalculateSchoolType(ApplyingStudent, UC_School);

                string SchoolTypeString = CalculateSchoolTypeString(ApplyingStudent, UC_School, SchoolType);

                string SchoolTypeColor = "";
                if (SchoolTypeBkColor[(int)SchoolType] != "")
                    SchoolTypeColor = String.Format("style=\"font-size: {0}px; background-color: {1}; color: {2};\"", FontSize - 1, SchoolTypeBkColor[(int)SchoolType], SchoolTypeTxColor[(int)SchoolType]);

                // Get Admission Result String
                string AdmissionResult = GetAdmissionResult(ApplyingStudent, UC_School);

                tableBody = String.Format("<div style =\"font-size: {0}px;\"><u>{1}</u>, {2}</div><div style =\"font-size: {0}px;\"><span {3}>{4}</span>, {5}</div>",
                                          FontSize - 1,
                                          WebUtility.HtmlEncode(AlternativeName),
                                          GetRanking(UC_School),
                                          SchoolTypeColor,
                                          SchoolTypeString,
                                          AdmissionResult);
            }

            return tableBody;
        }

        private string InsertUCSchools(SOF_Application ApplyingStudent, SOF_WorkList ApplyingSchool)
        {
            string tableBody = "";

            // Fill in school full name
            string UCSubSchoolPattern = @"(?i:(B|D|I|LA|M|R|SD|SB|SC))";
            string SubSchoolList = ApplyingSchool.School.Substring(3);

            tableBody += String.Format("<td><div style=\"font-size: {0}px;\"><b>University of California</b></div>", FontSize);

            MatchCollection Subschools = Regex.Matches(SubSchoolList, UCSubSchoolPattern);
            foreach (Match Subschool in Subschools)
            {
                switch (Subschool.Value.ToLower())
                {
                    case "b":
                        tableBody += InsertUCSchool(ApplyingStudent, "UCB", "Berkeley");
                        break;
                    case "d":
                        tableBody += InsertUCSchool(ApplyingStudent, "UCD", "Davis");
                        break;
                    case "i":
                        tableBody += InsertUCSchool(ApplyingStudent, "UCI", "Irvine");
                        break;
                    case "la":
                        tableBody += InsertUCSchool(ApplyingStudent, "UCLA", "Los Angeles");
                        break;
                    case "m":
                        tableBody += InsertUCSchool(ApplyingStudent, "UCM", "Merced");
                        break;
                    case "r":
                        tableBody += InsertUCSchool(ApplyingStudent, "UCR", "Riverside");
                        break;
                    case "sd":
                        tableBody += InsertUCSchool(ApplyingStudent, "UCSD", "San Diego");
                        break;
                    case "sb":
                        tableBody += InsertUCSchool(ApplyingStudent, "UCSB", "Santa Barbara");
                        break;
                    case "sc":
                        tableBody += InsertUCSchool(ApplyingStudent, "UCSC", "Santa Cruz");
                        break;
                    default:
                        break;
                }
            }

            // Create Cell
            string SchoolStatusString = "";
            string SchoolStatusBkColor = "";
            GetSchoolStatus(ApplyingSchool.Rally, ApplyingSchool.SchoolStats.RallyStatus, ref SchoolStatusString, ref SchoolStatusBkColor); ;

            tableBody += String.Format("<div style=\"font-size: {0}px;\">Rally {1}: <span style=\"background-color: {2};\">{3}</span></div></td>",
                                        FontSize,
                                        ApplyingSchool.Rally,
                                        SchoolStatusBkColor,
                                        SchoolStatusString);

            return tableBody;
        }

        private string CalculateSchoolTypeString(SOF_Application ApplyingStudent, School ApplyingSchool, SchoolAdmissionStatistics.SchoolListType AI_SchoolType)
        {
            string SchoolTypeString_AI = SchoolTypeText[(int)AI_SchoolType];

            StudentAdmissionResult SchoolResult = null;
            if (ApplyingStudent != null && ApplyingStudent.StudentObject != null)
                SchoolResult = ApplyingStudent.StudentObject.FindAdmissionResult(ApplyingSchool);

            string SchoolTypeString_Consultant = "";
            if (SchoolResult != null)
            {
                if (SchoolResult.Category == "Reach School")
                {
                    if (AI_SchoolType != SchoolAdmissionStatistics.SchoolListType.Reach && AI_SchoolType != SchoolAdmissionStatistics.SchoolListType.SuperReach)
                        SchoolTypeString_Consultant = "Reach";
                }
                else if (SchoolResult.Category == "Solid School")
                {
                    if (AI_SchoolType != SchoolAdmissionStatistics.SchoolListType.Match)
                        SchoolTypeString_Consultant = "Solid";
                }
                else if (SchoolResult.Category == "Safety School")
                {
                    if (AI_SchoolType != SchoolAdmissionStatistics.SchoolListType.Safety)
                        SchoolTypeString_Consultant = "Safety";
                }
                else
                    SchoolTypeString_Consultant = "Missing";
            }

            string SchoolTypeString = "";
            if (SchoolTypeString_Consultant != "")
                SchoolTypeString = String.Format("AI:{0}/C:{1}", SchoolTypeString_AI, SchoolTypeString_Consultant);
            else
                SchoolTypeString = SchoolTypeString_AI;

            return SchoolTypeString;
        }

        private string InsertSchool(SOF_Application ApplyingStudent, SOF_WorkList ApplyingSchool)
        {
            string tableBody = "";

            // Load School Full Name
            string EncodedSchoolName = "";
            if (ApplyingSchool.School.Equals("UC", StringComparison.CurrentCultureIgnoreCase))
            {
                EncodedSchoolName = WebUtility.HtmlEncode("University of California");
            }
            else
            {
                var SchoolInfo = SchoolDB.GetSchoolbyShortName(ApplyingSchool.School);
                if (SchoolInfo != null)
                    EncodedSchoolName = WebUtility.HtmlEncode(SchoolInfo.Name);
                else
                    EncodedSchoolName = WebUtility.HtmlEncode(ApplyingSchool.School);
            }

            string SchoolTypeColor = "";
            if (SchoolTypeBkColor[(int)ApplyingSchool.SchoolType] != "")
                SchoolTypeColor = String.Format("style=\"font-size: {0}px; background-color: {1}; color: {2};\"", FontSize, SchoolTypeBkColor[(int)ApplyingSchool.SchoolType], SchoolTypeTxColor[(int)ApplyingSchool.SchoolType]);

            string SchoolStatusString = "";
            string SchoolStatusBkColor = "";
            GetSchoolStatus(ApplyingSchool.Rally, ApplyingSchool.SchoolStats.RallyStatus, ref SchoolStatusString, ref SchoolStatusBkColor); ;

            // Calculate School Info
            string SchoolType = "";
            if (ApplyingSchool.SchoolObject != null)
            {
                string CollegeTypeRanking = GetRanking(ApplyingSchool.SchoolObject);

                string SchoolTypeString = CalculateSchoolTypeString(ApplyingStudent, ApplyingSchool.SchoolObject, ApplyingSchool.SchoolType);

                SchoolType = String.Format("<div style=\"font-size: {0}px;\">{1}: <span {2}>{3}</span></div>", 
                    FontSize, 
                    CollegeTypeRanking,
                    SchoolTypeColor,
                    SchoolTypeString);
            }

            // Special Type?
            string TypeColoring = "";
            string TypeString = "";

            if (ApplyingSchool.ApplicationType == SOF_WorkList.ApplicationSchoolType.Early1)
            {
                TypeColoring = "background-color: yellow; color: black;";
                //TypeString += "Early";
            }
            else if (ApplyingSchool.ApplicationType == SOF_WorkList.ApplicationSchoolType.Early2)
            {
                TypeColoring = "background-color: #FFE4B5; color: black;";
                //TypeString += "Early 2";
            }
            if (ApplyingSchool.NonSuppliment)
            {
                TypeColoring = "background-color: #B0E2FF; color: black;";
                if (TypeString != "")
                    TypeString += ", ";
                //TypeString += "No Suppliment";
            }
            if (TypeString != "")
                TypeString = ", " + TypeString;

            string SchoolStatusHTML = "";
            if (!ApplyingSchool.NonSuppliment)
                SchoolStatusHTML = String.Format(" <span style=\"background-color: {0};\">{1}</span>", SchoolStatusBkColor, SchoolStatusString);

            string AdmissionResult = GetAdmissionResult(ApplyingStudent, ApplyingSchool.SchoolObject);

            // Create Cell
            tableBody += String.Format("<td><div style=\"font-size: {0}px; {1}\"><b>{2}</b></div>{3}<div style=\"font-size: {0}px;\">Rally {4}{5}</div><div style=\"font-size: {0}px;\">Result: {6}</div></td>",
                            FontSize,
                            TypeColoring,
                            EncodedSchoolName,
                            SchoolType,
                            ApplyingSchool.Rally,
                            SchoolStatusHTML == "" ? "" : ": " + SchoolStatusHTML,
                            AdmissionResult);

            return tableBody;
        }

        private string InsertSchoolList(SOF_Application ApplyingStudent, IList<SOF_WorkList> ApplyingSchools, int RowNumber, bool NoSupplimentList)
        {
            string tableBody = "";
            int SchoolCount = 0;

            // Fill in Suppliment School
            int FromSchool = (RowNumber - 1) * SCHOOL_PER_ROW;
            int ToSchool = RowNumber * SCHOOL_PER_ROW;
            int RowSchoolCount = 0;

            foreach (var ApplyingSchool in ApplyingSchools)
            {
                if (SchoolCount == SCHOOL_PER_ROW)
                    break;

                if ((ApplyingSchool.ListType == "School") && (ApplyingSchool.NonSuppliment == NoSupplimentList)) // Suppliment Schools
                {
                    if ((RowSchoolCount >= FromSchool) && (RowSchoolCount < ToSchool))
                    {
                        // Fill in school full name
                        if (ApplyingSchool.School.StartsWith("UC-", StringComparison.CurrentCultureIgnoreCase))
                        {
                            tableBody += InsertUCSchools(ApplyingStudent, ApplyingSchool);
                        }
                        else
                        {
                            tableBody += InsertSchool(ApplyingStudent, ApplyingSchool);
                        }
                        SchoolCount += 1;
                    }
                    RowSchoolCount += 1;
                }
            }

            // Filling in padding cell
            for (int i = 0; i < SCHOOL_PER_ROW - SchoolCount; i++)
            {
                tableBody += "<td></td>";
            }

            return tableBody;
        }
    }
}
